package com.victor.utils.wxlogin;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.victor.pay.app.PayCommonUtil;
import com.victor.utils.HttpClientUtil;

public class PublicNumberUtil {
	private static final Logger logger = LoggerFactory.getLogger(PublicNumberUtil.class);
	public final static String js_api_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";

	public static JsapiTicket getJsapiTicket(String appid, String appsecret) {
		String access_token = access_token(appid, appsecret);
		JsapiTicket ticket = new JsapiTicket();

		String requestUrl = js_api_ticket_url.replace("ACCESS_TOKEN", access_token);
		String result = PayCommonUtil.httpsRequest(requestUrl, "GET", null);
		JSONObject jsonObject = JSONObject.parseObject(result);
		if (jsonObject.getString("errcode").equals("0")) {
			ticket.setTicket(jsonObject.getString("ticket"));
			ticket.setExpiresIn(jsonObject.getString("expires_in"));
		} else {
			logger.error(jsonObject.toJSONString());
		}
		return ticket;

	}

	private static String access_token(String appid, String appsecret) {
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret="
				+ appsecret;
		String responseBody = HttpClientUtil.doGet(url);
		JSONObject jsonObject = JSON.parseObject(responseBody);
		String result = null;
		if (null != responseBody) {
			try {
				result = jsonObject.getString("access_token");
				Integer errorCode = jsonObject.getInteger("errcode");
				if (errorCode != null) {
					String errorMsg = jsonObject.getString("errmsg");
					logger.error("获取用户信息失败 errcode:{} errmsg:{}", errorCode, errorMsg);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	// 官网提供的工具类 需要自己增加appId
	public static Map<String, String> sign(String jsapi_ticket, String url, String appid) {
		Map<String, String> ret = new HashMap<String, String>();
		String nonce_str = create_nonce_str();
		String timestamp = create_timestamp();
		String string1;
		String signature = "";
		// 注意这里参数名必须全部小写，且必须有序
		string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(string1.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		ret.put("url", url);
		// 注意这里 要加上自己的appId
		ret.put("appId", appid);
		ret.put("jsapi_ticket", jsapi_ticket);
		ret.put("nonceStr", nonce_str);
		ret.put("timestamp", timestamp);
		ret.put("signature", signature);

		return ret;
	}

	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	private static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}

	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

}
